package cn.yunhe.springboot_shiro.config;

import cn.yunhe.springboot_shiro.dao.UserMapper;
import cn.yunhe.springboot_shiro.entity.User;
import lombok.Getter;
import lombok.Setter;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Set;

/**
 * 身份校验核心类
 */
@Getter
@Setter

public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    private UserMapper userMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入授权");
        User user = (User) principalCollection.getPrimaryPrincipal();
        String name = user.getUsername();
        Set<String> roles = userMapper.getRoles(name);
        //打印用户的角色
        for (String s : roles) {
            System.out.println(s);
        }
        Set<String> permissions = userMapper.getPermissions(name);
        //打印用户的权限
        for (String s : permissions) {
            System.out.println(s);
        }

        SimpleAuthorizationInfo author = new SimpleAuthorizationInfo();
        author.setRoles(roles);
        author.setStringPermissions(permissions);
        return author;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("进入认证");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String name = token.getUsername();
        User user = userMapper.login(name);
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }
}
